﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ReportingSystem.IRepository;
using ReportingSystem.Repository;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ReportingSystem.Controllers
{
    /// <summary>
    /// 图片上传缓存
    /// </summary>
    public class ImageController : BaseController
    {
        private AppDbContext _context;
        public ImageController(IUserRepository userService, IRepairsRepository repairsRepository)
            : base(userService, repairsRepository)
        {
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ActionResult UploadImg()
        {
            //获取微信小程序图片
            //var count = Request.Form.Count;
            int code = 0;
            string message = "";
            var data = "";
           
            //返回的文件地址
            var now = DateTime.Now;
            //文件存储路径
            var filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //当前web目录
            var webRootPath = "D:/360MoveData/Users/13454/Desktop/大四12周报修系统/ReportingSystem/ReportingSystem/UploadImage";
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                var file = Request.Form.Files[0];
                if (file != null)
                {
                    #region  图片文件的条件判断
                    //文件后缀
                    var fileExtension = Path.GetExtension(file.FileName);

                    //判断后缀是否是图片
                    const string fileFilt = ".gif|.jpg|.jpeg|.png";
                    if (fileExtension == null)
                    {
                        code = 500;
                        message = "上传的文件没有后缀！！";
                        //break;
                    }
                    if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                    {
                        code = 500;
                        message = "请上传jpg、png、gif格式的图片！！";
                        //break;
                    }

                    //判断文件大小    
                    long length = file.Length;
                    if (length > 1024 * 1024 * 2) //2M
                    {
                        code = 500;
                        message = "上传的文件不能大于2M！！";
                        //break;
                    }

                    #endregion

                    var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                    var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                    var saveName = strDateTime + strRan + fileExtension;

                    //插入图片数据                 
                    using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    //filenames.Add(webRootPath + filePath + saveName);
                    code = 200;
                    message = "上传文件成功！！";
                    data = webRootPath + filePath + saveName;
                }
                else {
                    code = 500;
                    message = "请上传文件！！";
                }
                return new JsonResult(new { code, message, data });
            }
            catch (Exception ex)
            {
                code = 500;
                message = "请上传图片！";
                return new JsonResult(new { code, message });
            }
        }

        /// <summary>
        /// 图片加载
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        //public IActionResult GetImage( string name)
        //{
        //    var appPath = AppContext.BaseDirectory.Split("\\bin\\")[0] + "/image/";
        //    var errorImage = appPath + "404.png";//没有找到图片
        //    var imgPath = string.IsNullOrEmpty(name) ? errorImage : appPath + name;
        //    //获取图片的返回类型
        //    var contentTypDict = new Dictionary<string, string> {
        //        {"jpg","image/jpeg"},
        //        {"jpeg","image/jpeg"},
        //        {"jpe","image/jpeg"},
        //        {"png","image/png"},
        //        {"gif","image/gif"},
        //        {"ico","image/x-ico"},
        //        {"tif","image/tiff"},
        //        {"tiff","image/tiff"},
        //        {"fax","image/fax"},
        //        {"wbmp","image//vnd.wap.wbmp"},
        //        {"rp","image/vnd.rn-realpix"}
        //    };
        //    var contentTypeStr = "image/jpeg";
        //    var imgTypeSplit = name.Split('.');
        //    var imgType = imgTypeSplit[imgTypeSplit.Length - 1].ToLower();
        //    //未知的图片类型
        //    if (!contentTypDict.ContainsKey(imgType))
        //    {
        //        imgPath = errorImage;
        //    }
        //    else
        //    {
        //        contentTypeStr = contentTypDict[imgType];
        //    }
        //    //图片不存在
        //    if (!new FileInfo(imgPath).Exists)
        //    {
        //        imgPath = errorImage;
        //    }
        //    //原图
        //    //if (width <= 0)
        //    {
        //        using (var sw = new FileStream(imgPath, FileMode.Open))
        //        {
        //            var bytes = new byte[sw.Length];
        //            sw.Read(bytes, 0, bytes.Length);
        //            sw.Close();
        //            return new FileContentResult(bytes, contentTypeStr);
        //        }
        //    }
        //return new FileContentResult(bytes, contentTypeStr);
        //缩小图片
        //using (var imgBmp = new Bitmap(imgPath))
        //{
        //    //找到新尺寸
        //    var oWidth = imgBmp.Width;
        //    var oHeight = imgBmp.Height;
        //    var height = oHeight;
        //    if (width > oWidth)
        //    {
        //        width = oWidth;
        //    }
        //    else
        //    {
        //        height = width * oHeight / oWidth;
        //    }
        //    var newImg = new Bitmap(imgBmp, width, height);
        //    newImg.SetResolution(72, 72);
        //    var ms = new MemoryStream();
        //    newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        //    var bytes = ms.GetBuffer();
        //    ms.Close();
        //    return new FileContentResult(bytes, contentTypeStr);
        //}
        public async Task<IActionResult> ShowImage(string str)
        {
            using (var sw = new FileStream(str, FileMode.Open))
            {
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, "image/jpeg");
            }
            //return PhysicalFile(str, "image/jpeg");
        }
        }
}